Skip to content

fix(spanner): forward client_options in spanner_dbapi.connect() - #19183

Merged
sakthivelmanii merged 4 commits into
mainfrom
fix-spanner-dbapi-client-options
Nov 24, 2026
Merged

sakthivelmanii merged 4 commits into
mainfrom
fix-spanner-dbapi-client-options

Conversation

@sakthivelmanii

Copy link
Copy Markdown
Contributor

Problem Statement

  • Calling spanner_dbapi.connect() with client_options on standard Cloud Spanner connections (using Application Default Credentials, explicit Credentials, or a service account JSON path) silently ignored client_options and fell back to the default Spanner endpoint instead of honoring settings such as universe_domain or api_endpoint.
  • Passing client_options alongside a pre-built client was also silently ignored instead of raising an error.

Solution

  • Added client_options as an explicit optional parameter on spanner_dbapi.connect() so it is never stored as a connection variable on Connection.
  • Forwarded client_options (ClientOptions or dict) to spanner.Client and spanner.Client.from_service_account_json() across all connection modes.
  • Raised ValueError when both a pre-built client and non-None client_options are supplied to spanner_dbapi.connect() so custom client options are never silently ignored.

## Problem Statement

- Calling `spanner_dbapi.connect()` with `client_options` on standard Cloud Spanner connections (using Application Default Credentials, explicit `Credentials`, or a service account JSON path) silently ignored `client_options` and fell back to the default Spanner endpoint instead of honoring settings such as `universe_domain` or `api_endpoint`.
- Passing `client_options` alongside a pre-built `client` was also silently ignored instead of raising an error.

## Solution

- Added `client_options` as an explicit optional parameter on `spanner_dbapi.connect()` so it is never stored as a connection variable on `Connection`.
- Forwarded `client_options` (`ClientOptions` or `dict`) to `spanner.Client` and `spanner.Client.from_service_account_json()` across all connection modes.
- Raised `ValueError` when both a pre-built `client` and non-`None` `client_options` are supplied to `spanner_dbapi.connect()` so custom client options are never silently ignored.
@sakthivelmanii
sakthivelmanii requested a review from a team as a code owner November 23, 2026 03:35

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for client_options in the Spanner DB-API connect function, allowing configuration of custom endpoints and universe domains. It also prevents client_options from being silently ignored when a custom client is provided. However, the newly added end-to-end tests in test_connection.py fail to provide the required database_id positional argument to the connect function, which will cause TypeError exceptions when the tests are run.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for the client_options parameter in the Spanner DB-API connect function, allowing users to configure options like api_endpoint and universe_domain. It updates the connection logic to pass these options to the client, prevents their use when a custom client is provided, and adds comprehensive unit tests to validate various scenarios. I have no feedback to provide as the changes are well-implemented and thoroughly tested.

@daniel-sanche

Copy link
Copy Markdown
Contributor

Shouldn't this be marked as a fix instead of a chore? Chores aren't shown in release notes, and IIRC won't trigger a new release PR on their own

@sakthivelmanii sakthivelmanii changed the title chore(spanner): forward client_options in spanner_dbapi.connect() fix(spanner): forward client_options in spanner_dbapi.connect() Nov 23, 2026

@olavloite olavloite left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note on context: client_options in spanner_dbapi.connect() originally started in #1370 as a test-only kwargs hook (gated on AnonymousCredentials), became an implicit public option in #17246 when connect()'s docstring recommended it for Spanner Omni, and is now being formalized as an explicit connection parameter. Since tightening existing overlapping options into errors would now be a breaking change, documenting precedence clearly is especially important.

A few cleanups to address before merging:

  1. Validate and unify client_options handling in google/cloud/spanner_dbapi/connection.py:

    • Move import copy from line 1039 to the top of the module.
    • Extract the omni client_options resolution and shallow-copy logic (lines 996–1000 and 1033–1042) into a small helper that validates client_options type. Passing a non-dict, non-ClientOptions object alongside experimental_host currently hits copy.copy(client_options).api_endpoint = host_endpoint and raises AttributeError instead of TypeError/ValueError, and the fallback branch at line 999 is also uncovered by tests.
  2. Assert the exception message in tests/unit/spanner_dbapi/test_connection.py (line 1027):

    • Replace bare with self.assertRaises(ValueError): with assertRaisesRegex (or assert on ctx.exception) to verify the expected error message.
  3. Document precedence and fix docstring ordering in connect() (google/cloud/spanner_dbapi/connection.py):

    • Document precedence/interactions for the overlapping connection options (SPANNER_EMULATOR_HOST overriding credentials/instance_type/api_endpoint, experimental_host overriding client_options.api_endpoint, instance_type="omni" overriding project and credentials, and use_plain_text/Omni TLS parameters only applying when instance_type="omni").
    • Move :param client_options: above :returns:/:rtype:.
  4. Squash-merge commit title:

    • Ensure the squash commit uses the fix(spanner): ... PR title rather than the local chore(spanner): ... commit message so it is included in release notes and triggers a release PR.

@sakthivelmanii

Copy link
Copy Markdown
Contributor Author

@olavloite Thanks for the review! Addressed all 4 items in the latest commit: moved import copy to module level, validated client_options type (ClientOptions or dict) up front and extracted _resolve_omni_client_options with tests, asserted the unknown_option message in test_connection.py, and documented option precedence with :param client_options: above :returns:. The PR title is also fix(spanner): forward client_options in spanner_dbapi.connect() so squash-merging will use that title.

@olavloite olavloite left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

There are a few minor (pre-existing) inconsistencies in the docstring remaining, but feel free to merge as-is, as the current implementation is a significant improvement.

  1. SPANNER_EMULATOR_HOST vs. instance_type="omni" and credentials file paths

    • In connect(), the instance_type == "omni" block runs before spanner.Client(...) checks SPANNER_EMULATOR_HOST. As a result, calling connect(..., instance_type="omni") without api_endpoint / experimental_host raises ValueError even when SPANNER_EMULATOR_HOST is set (whereas spanner.Client(..., instance_type="omni") connects to the emulator). When an endpoint is provided alongside SPANNER_EMULATOR_HOST, connect() also overwrites project to "default" before spanner.Client switches to the emulator.
    • When credentials is a file path (str), Client.from_service_account_json() is still called and reads the file from disk before spanner.Client overrides credentials for the emulator.
  2. credentials as a file path (str) bypasses experimental_host and instance_type

    • Because if isinstance(credentials, str): wraps the experimental_host / instance_type logic in an else: branch, passing a credential file path together with instance_type="omni" (or an invalid instance_type), experimental_host, or Omni TLS/auth options silently ignores those options and connects via Client.from_service_account_json().
  3. username / password when instance_type != "omni"

    • connect() does not forward username or password to spanner.Client(...), so passing them without instance_type="omni" (or experimental_host) silently ignores them instead of raising ValueError as spanner.Client(...) does. When migrating from experimental_host to client_options={"api_endpoint": ...}, forgetting instance_type="omni" will therefore fall back to credentials / ADC and ignore ca_certificate / mTLS options.

I think that this docstring would describe the actual behavior a bit better:

    .. note::

        **Option precedence and interactions:**

        - ``credentials`` as a file path (``str``) takes precedence over
          ``experimental_host``, ``instance_type``, and the Omni auth/TLS
          options, connecting via :meth:`Client.from_service_account_json`.
        - ``SPANNER_EMULATOR_HOST`` (environment variable) overrides
          ``credentials`` (unless passed as a ``str`` file path, which is
          still loaded before the override) and ``api_endpoint`` to connect
          to the Spanner emulator using anonymous credentials. Note that
          ``instance_type="omni"`` still validates that an endpoint is set
          and overrides ``project`` to ``"default"`` before
          ``SPANNER_EMULATOR_HOST`` takes effect.
        - ``experimental_host`` (deprecated) forces ``instance_type="omni"``
          (overriding any ``instance_type`` value) and overrides
          ``client_options.api_endpoint``.
        - ``instance_type="omni"`` (when ``credentials`` is not a ``str``)
          overrides ``project`` (to ``"default"``) and ``credentials``
          (using ``SpannerOmniCredentials`` when both ``username`` and
          ``password`` are provided, or ``AnonymousCredentials`` otherwise).
        - ``use_plain_text``, ``ca_certificate``, ``client_certificate``,
          ``client_key``, ``username``, and ``password`` apply only when
          ``instance_type="omni"`` (and ``credentials`` is not a ``str``),
          and are silently ignored otherwise.
        - Providing both a custom ``client`` and non-``None``
          ``client_options`` raises :class:`ValueError` (other client-creation
          options are ignored when a custom ``client`` is provided).

@sakthivelmanii

Copy link
Copy Markdown
Contributor Author

@olavloite Good points — updated the connect() docstring precedence note to match your suggested wording.

@sakthivelmanii
sakthivelmanii enabled auto-merge (squash) November 24, 2026 09:52
@sakthivelmanii
sakthivelmanii merged commit 9529bf8 into main Nov 24, 2026
85 checks passed
@sakthivelmanii
sakthivelmanii deleted the fix-spanner-dbapi-client-options branch November 24, 2026 10:12
daniel-sanche pushed a commit that referenced this pull request Nov 25, 2026
## Problem Statement

- Calling `spanner_dbapi.connect()` with `client_options` on standard
Cloud Spanner connections (using Application Default Credentials,
explicit `Credentials`, or a service account JSON path) silently ignored
`client_options` and fell back to the default Spanner endpoint instead
of honoring settings such as `universe_domain` or `api_endpoint`.
- Passing `client_options` alongside a pre-built `client` was also
silently ignored instead of raising an error.

## Solution

- Added `client_options` as an explicit optional parameter on
`spanner_dbapi.connect()` so it is never stored as a connection variable
on `Connection`.
- Forwarded `client_options` (`ClientOptions` or `dict`) to
`spanner.Client` and `spanner.Client.from_service_account_json()` across
all connection modes.
- Raised `ValueError` when both a pre-built `client` and non-`None`
`client_options` are supplied to `spanner_dbapi.connect()` so custom
client options are never silently ignored.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants